package com.winit.cloudlink.common.utils;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {
    public static String jsonPost(String urlString, String parametersString) throws IOException {
        URL url = null;
        HttpURLConnection urlConnection = null;
        InputStream in = null;
        StringBuilder sb = new StringBuilder();
        try {
            url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setAllowUserInteraction(true);
            //添加请求头
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            urlConnection.setRequestProperty("Accept", "*/*");

            //发送Post请求
            urlConnection.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
            wr.writeBytes(parametersString);
            wr.flush();
            wr.close();

            int responseCode = urlConnection.getResponseCode();
            if (responseCode == 200 || responseCode == 201 || responseCode == 206) {            // 判断请求是否成功处理
                in = urlConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                if (bufferedReader != null) {
                    int cp;
                    while ((cp = bufferedReader.read()) != -1) {
                        sb.append((char) cp);
                    }
                    bufferedReader.close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Exception while calling URL:" + url, e);
        } finally {
            if (in != null) {
                in.close();
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        return sb.toString();
    }

}
